package cn.lzc.jl.service.conf.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import cn.lzc.jl.service.util.codec.DES3Helper;
import cn.lzc.jl.service.util.constant.Constant;

/**
 * 
 * <消息头校验>
 * <功能详细描述>
 * 
 * @author  sunliang
 * @version  [版本号, 2018年9月4日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class HttpInputMessageHandle implements HttpInputMessage
{
    /** 消息头     */
    private HttpHeaders headers;
    
    /** 消息体 */
    private InputStream body;
    
    public HttpInputMessageHandle(HttpInputMessage inputMessage)
        throws Exception
    {
        this.headers = inputMessage.getHeaders();
        this.body = IOUtils.toInputStream(
            DES3Helper.decrypt(easpString(IOUtils.toString(inputMessage.getBody(), Constant.EN_CODE))),
            Constant.EN_CODE);
    }
    
    @Override
    public HttpHeaders getHeaders()
    {
        return headers;
    }
    
    @Override
    public InputStream getBody()
        throws IOException
    {
        return body;
    }
    
    /**
    * 校验消息头是否正确
    * @param requestData 消息头
    * @return 
    */
    public String easpString(String reqDate)
    {
        if (StringUtils.isNotEmpty(reqDate))
        {
            if (!reqDate.startsWith(Constant.REQ_HEADER))
            {
                throw new RuntimeException("消息头【REQ_HEADER】缺失异常！");
            }
            else
            {
                int closeLen = reqDate.length() - 2;
                int openLen = Constant.REQ_HEADER.length() + 1;
                return StringUtils.substring(reqDate, openLen, closeLen);
            }
        }
        return "";
    }
    
}
